package com.pay.paytoken.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.pay.paytoken.R;
import com.pay.paytoken.activity.BindMsgActivity;
import com.pay.paytoken.activity.lock.LockManager;
import com.pay.paytoken.base.BaseFragment;
import com.pay.paytoken.listener.SettingFirstListener;
import com.pay.paytoken.paytoken.PayTokenConstant;
import com.zhy.autolayout.AutoLinearLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import apiUtils.apis.GetDataTimeAPI;
import apiUtils.apis.account.BaseAccountAPI;
import apiUtils.apis.account.FreezeBindingAccountAPI;
import apiUtils.apis.account.RemoveBindingAccountAPI;
import apiUtils.models.AccountStateModel;
import appUtils.CustomAlertDoubleBtnDialog;
import appUtils.CustomSingleInputDialog;
import appUtils.HiddenRule;
import appUtils.LogUtil;
import appUtils.PayMD5Util;
import appUtils.PayTokenException;
import appUtils.SharedPreferencesManager;
import appUtils.ToastUtil;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import constant.AppConstants;
import totpUtils.SPUtils;
import totpUtils.TotpUtil;

import static apiUtils.models.AccountStateModel.BINDING;
import static appUtils.SharedPreferencesManager.BINDING_LIST;
import static appUtils.SharedPreferencesManager.FIRST;
import static appUtils.SharedPreferencesManager.ISLIST;
import static appUtils.SharedPreferencesManager.SECRET_KEY;
import static appUtils.SharedPreferencesManager.VERIFY_PHONE;
import static com.pay.paytoken.paytoken.PayTokenConstant.bindtype_EXTRA;
import static totpUtils.config.MTokenConstants.PREFS_SERVICE_TIME_REDUCE;

public class MainUserManagerFragment extends BaseFragment {
    private static final int NOTIFY = 0x1;
    private static final int VERIFY = 0x1 << 1;
    private static final int ISFIRST = 0x1 << 2;
    private static final int CODE_INPUT = 0x1 << 4;
    private final List<AccountStateModel> mList = new ArrayList<>();
    private final DialogInterface.OnKeyListener mKeylistener = new DialogInterface.OnKeyListener() {
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            return keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0;
        }
    };
    @Bind(R.id.layout_title_textName)
    TextView mLayoutTitleTextName;
    @Bind(R.id.layout_title_iv_left)
    ImageButton mLayoutTitleIvLeft;
    @Bind(R.id.layout_title_ivSecond)
    ImageButton mLayoutTitleIvSecond;
    @Bind(R.id.layout_account_binding)
    AutoLinearLayout mFirstAccountBinding;
    @Bind(R.id.layout_account_bind_info)
    AutoLinearLayout mLayoutAccountBindInfo;
    @Bind(R.id.tv_account_company_name)
    TextView mTvAccountCompanyName;
    @Bind(R.id.tv_account_info)
    TextView mTvAccountInfo;
    private SettingFirstListener mSettingFirstListener;
    private Gson mGson;
    private CustomSingleInputDialog mCustomSingleInputDialog;
    private CustomAlertDoubleBtnDialog mCustomAlertDoubleBtnDialog;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case NOTIFY:
                    boolean empty = mList.isEmpty();
                    initViews(empty);
                    break;
                case ISFIRST:
                    isFirst(true);
                    LockManager.getInstance().resetAllPwds();
                    break;
                case VERIFY:
                    AlertDialog dialog = new AlertDialog.Builder(getActivity()).setMessage(R.string.failed_phone_validation).create();
                    dialog.setOnKeyListener(mKeylistener);
                    dialog.setCanceledOnTouchOutside(false);
                    dialog.show();
                    break;
            }
        }
    };

    @Override
    public void onStart() {
        super.onStart();
        mPhoneUtil.getDevicePermission();
    }

    private void isFirst(boolean isFirst) {
        mSharedPreferencesManager.saveBoolean(SharedPreferencesManager.FIRST, isFirst);
        mSettingFirstListener.settingFirst(isFirst);
    }

    @Override
    public int setView() {
        return R.layout.fragment_main_bottom_fragment1;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        mGson = new Gson();
        mList.clear();
        mCustomSingleInputDialog = new CustomSingleInputDialog(mActivity);
        mCustomSingleInputDialog.setTitleText(getString(R.string.please_enter_login_password));
        mCustomSingleInputDialog.setYesBtnText(getString(R.string.confirm));
        mCustomAlertDoubleBtnDialog = new CustomAlertDoubleBtnDialog(mActivity);
    }

    @Override
    public void initView() {
        showProgress(R.string.loadding);
        getBindingList();

        boolean isFirst = mSharedPreferencesManager.readBoolean(FIRST, true);
        initViews(isFirst);
        mLayoutTitleIvLeft.setVisibility(View.INVISIBLE);
        mLayoutTitleTextName.setText(R.string.home_bottom_text1);
        /*mLayoutTitleIvSecond.setImageResource(R.drawable.icon_title_add);
        mLayoutTitleIvSecond.setVisibility(View.VISIBLE);*/
    }

    private void initViews(boolean isFirst) {
        mFirstAccountBinding.setVisibility(isFirst ? View.VISIBLE : View.GONE);
        mLayoutAccountBindInfo.setVisibility(isFirst ? View.GONE : View.VISIBLE);
    }

    private void initLayoutInfo(List<AccountStateModel> list) {
        if (list == null) {
            mLayoutAccountBindInfo.setVisibility(View.GONE);
            return;
        }
        if (list.size() > 0) {
            mLayoutAccountBindInfo.setVisibility(View.VISIBLE);
            AccountStateModel accountStateModel = list.get(0);
            HiddenRule hiddenRule = new HiddenRule();
            mTvAccountCompanyName.setText(hiddenRule.nameHidden(accountStateModel.getUserCompanyName()));
            mTvAccountInfo.setText(hiddenRule.accountCommonHidden(accountStateModel.getUserAccount()));
        } else {
            mLayoutAccountBindInfo.setVisibility(View.GONE);
        }
    }

    private void getBindingList() {
        String bindListStr = mSharedPreferencesManager.readString(SharedPreferencesManager.BINDING_LIST, "");
        addModel(bindListStr);
        initLayoutInfo(mList);
        dismisProgress();
        mHandler.sendEmptyMessage(NOTIFY);
    }

    private void freezeBindAccount(final AccountStateModel stateModel) {
        CustomSingleInputDialog.onYesOnclickListener listener = new CustomSingleInputDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                String pwd = PayMD5Util.getMD5Lower(mCustomSingleInputDialog.getUserPwd());
                if (TextUtils.isEmpty(mPhoneUtil.getDeviceIDStr())) {
                    mPhoneUtil.getDevicePermission();
                    return;
                }
                String deviceId = mPhoneUtil.getDeviceIDStr();
                if (!TextUtils.isEmpty(pwd) && !TextUtils.isEmpty(deviceId)) {
                    showProgress(R.string.loadding);
                    new FreezeBindingAccountAPI(mContext).freezeBindingAccount(
                            stateModel.getUserAccountType(), stateModel.getUserAccountId(), pwd, deviceId, new BaseAccountAPI.Listener() {
                                @Override
                                public void onSuccess(JSONObject object) {
                                    dismisProgress();
                                    if (null != object) {
                                        LogUtil.log("FreezeBindingAccountAPI success");
                                        if (TextUtils.isEmpty(object.toString())) {
                                            return;
                                        }
                                        mList.remove(0);
                                        if (mList.size() < 1) {
                                            mHandler.sendEmptyMessage(ISFIRST);
                                        }
                                        mHandler.sendEmptyMessage(NOTIFY);
                                        mSharedPreferencesManager.saveString(BINDING_LIST, mGson.toJson(mList));
                                        mSharedPreferencesManager.saveBoolean(VERIFY_PHONE, true);
                                        try {
                                            ToastUtil.showShort(object.getString("message"));
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                            ToastUtil.showShort(R.string.freeze_success);
                                            PayTokenException.getInstance().saveExceptionFile("" +
                                                    "MainUserManagerFragment freezeBindAccount " +
                                                    "JSONException error: " + e.getMessage());
                                        }
                                    } else {
                                        LogUtil.log("FreezeBindingAccountAPI failure object null");
                                        ToastUtil.showShort(R.string.freeze_failure);
                                    }
                                }

                                @Override
                                public void onFailure(int code, String message) {
                                    LogUtil.log("FreezeBindingAccountAPI failure");
                                    dismisProgress();
                                    if (!TextUtils.isEmpty(message)) {
                                        ToastUtil.showShort(message);
                                    } else {
                                        ToastUtil.showShort(R.string.freeze_failure);
                                    }

                                }
                            });
                } else {
                    ToastUtil.showShort(R.string.account_password_fault);
                }

            }
        };
        mCustomSingleInputDialog.setYesBtnText(getString(R.string.determine_the_freeze));
        mCustomSingleInputDialog.setOnYesOnclickListener(listener);
        mCustomSingleInputDialog.showCustomDialog();
    }

    private void removeBindAccount(final AccountStateModel stateModel) {
        if (TextUtils.isEmpty(mPhoneUtil.getDeviceIDStr())) {
            mPhoneUtil.getDevicePermission();
            return;
        }
        String deviceId = mPhoneUtil.getDeviceIDStr();
        if (!TextUtils.isEmpty(deviceId)) {
            showProgress(R.string.loadding);
            new RemoveBindingAccountAPI(mContext).removeBindingAccount(
                    stateModel.getUserAccountType(), stateModel.getUserAccountId(), deviceId, new BaseAccountAPI.Listener() {
                        @Override
                        public void onSuccess(JSONObject object) {
                            dismisProgress();
                            if (null != object) {
                                LogUtil.log("FreezeBindingAccountAPI success");
                                if (TextUtils.isEmpty(object.toString())) {
                                    return;
                                }
                                if (mList.size() > 0) {
                                    mList.remove(0);
                                }
                                if (mList.size() < 1) {
                                    mHandler.sendEmptyMessage(ISFIRST);
                                }
                                mHandler.sendEmptyMessage(NOTIFY);
                                mSharedPreferencesManager.saveString(BINDING_LIST, mGson.toJson(mList));
                                mSharedPreferencesManager.saveBoolean(VERIFY_PHONE, true);
                                try {
                                    ToastUtil.showShort(object.getString("message"));
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                    ToastUtil.showShort(R.string.unbundling_success);
                                    PayTokenException.getInstance().saveExceptionFile("" +
                                            "MainUserManagerFragment removeBindAccount JSONException error: "
                                            + e.getMessage());
                                }
                            } else {
                                ToastUtil.showShort(R.string.unbinding_failure);
                            }
                        }

                        @Override
                        public void onFailure(int code, String message) {
                            LogUtil.log("FreezeBindingAccountAPI failure");
                            dismisProgress();
                            if (!TextUtils.isEmpty(message)) {
                                ToastUtil.showShort(message);
                            } else {
                                ToastUtil.showShort(R.string.unbinding_failure);
                            }
                        }
                    });
        }
    }

    @OnClick({R.id.btn_bindtype_wallet, R.id.btn_bindtype_merchant,
            R.id.btn_bind_account_freeze, R.id.btn_bind_account_thaw})
    public void onViewClicked(View view) {
        Intent intent = new Intent();
        int type;
        switch (view.getId()) {
            case R.id.btn_bindtype_wallet:
                type = PayTokenConstant.BINDTYPE_WALLET_REQUESTCODE;
                intent.setClass(mActivity, BindMsgActivity.class);
                intent.putExtra(bindtype_EXTRA, type);
                getActivity().startActivityForResult(intent, AppConstants.MAINACTIVITY_MSG_REQUEST);
                break;
            case R.id.btn_bindtype_merchant:
                type = PayTokenConstant.BINDTYPE_SHANGHU_REQUESTCODE;
                intent.setClass(mActivity, BindMsgActivity.class);
                intent.putExtra(bindtype_EXTRA, type);
                getActivity().startActivityForResult(intent, AppConstants.MAINACTIVITY_MSG_REQUEST);
                break;
            case R.id.btn_bind_account_freeze:
                mCustomAlertDoubleBtnDialog.setTitle(getString(R.string.you_are_going_to_freeze) + mTvAccountInfo.getText().toString());
                mCustomAlertDoubleBtnDialog.setRightBtnLabel(getString(R.string.confirm_the_freeze));
                mCustomAlertDoubleBtnDialog.setMsg(getString(R.string.freeze_tips));
                CustomAlertDoubleBtnDialog.commitClickListener listener = new CustomAlertDoubleBtnDialog.commitClickListener() {
                    @Override
                    public void onClick() {
                        AccountStateModel stateModel = mList.get(0);
                        if (stateModel.getState().equals(BINDING)) {
                            freezeBindAccount(stateModel);
                        }
                    }
                };
                mCustomAlertDoubleBtnDialog.setCommitClickListener(listener);
                mCustomAlertDoubleBtnDialog.showDialog();
                break;
            case R.id.btn_bind_account_thaw:
                mCustomAlertDoubleBtnDialog.setTitle(getString(R.string.are_you_sure_you_want_to_unbind));
                mCustomAlertDoubleBtnDialog.setRightBtnLabel(getString(R.string.confirm_the_unbundling));
                mCustomAlertDoubleBtnDialog.setMsg(getString(R.string.thaw_tips));
                listener = new CustomAlertDoubleBtnDialog.commitClickListener() {
                    @Override
                    public void onClick() {
                        AccountStateModel stateModel = mList.get(0);
                        if (stateModel.getState().equals(BINDING)) {
                            removeBindAccount(stateModel);
                        }
                    }
                };
                mCustomAlertDoubleBtnDialog.setCommitClickListener(listener);
                mCustomAlertDoubleBtnDialog.showDialog();
                break;
            default:
                break;
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    public MainUserManagerFragment setSettingChangeListener(SettingFirstListener listener) {
        mSettingFirstListener = listener;
        return this;
    }

    private void initTotp() {
        String secretKey = mSharedPreferencesManager.readString(SECRET_KEY, "");
        if (!TextUtils.isEmpty(secretKey)) {
            TotpUtil.init(secretKey);// init SEED
        }
    }

    private void addModel(String decodeMsg) {
        List<AccountStateModel> model = mGson.fromJson(decodeMsg, new TypeToken<List<AccountStateModel>>() {
        }.getType());
        if (null != model) {
            mList.clear();
            mList.addAll(model);
        }
    }

    public void doAfterBindSuccess() {
        mList.clear();
        mSharedPreferencesManager.saveBoolean(ISLIST, false);
        showProgress(R.string.loadding);
        getBindingList();
        initTotp();
        isFirst(false);
        LockManager.getInstance().resetLock(mContext);
        correctTime();
        LogUtil.log("doAfterBindSuccess");
    }

    protected void correctTime() {
        new GetDataTimeAPI().getServerTime(new GetDataTimeAPI.Listener() {
            @Override
            public void onSuccess(long deltaTime) {
                SPUtils.put(PREFS_SERVICE_TIME_REDUCE, deltaTime);
            }

            @Override
            public void onFailure(int code) {
            }
        });
    }
}
